<template>
  <div>
    <div class="page_title">新型标准化技术组织</div>
    <FormTable :formRules="formRules" :tableData="tableData" :columns="columns" :total="total" :currentPage="pageIndex"
      :pageSize="pageSize" @changeTableData="changeTableData" @queryTable="queryTable" maxHeight="750px">
      <template #tableTabs>
        <div style="display: flex;justify-content: end;margin-bottom: 16px;">
          <el-button type="primary" @click="openImportDialog">导入</el-button>
          <el-button type="primary" @click="edit()">新增</el-button>
        </div>
      </template>
      <template #operator="{ slotProps }" class="table_button_list">
        <span class="table_button" style="margin-left: 10px;" @click="edit(slotProps)">修改</span>
        <el-popconfirm title="确定删除该条数据么?" @confirm="del(slotProps)">
          <template #reference>
            <span class="table_button" style="margin-left: 10px;color:#F56C6C">删除</span>
          </template>
        </el-popconfirm>
      </template>
    </FormTable>
    <v-form v-model="dialogVisible" :dataForm="dialogForm" v-if="dialogVisible" @close="dialogVisible = false"
      :isDetail="isDetail" :isFabu="isFabu" @getDatas="queryTable()" />
    <el-dialog title="导入" v-model="showImportDialog" width="500px" center>
      <div style="text-align: center;" v-if="showImportDialog">
        <br>
        <el-button @click="downloadTemplate()">第一步：下载模板</el-button>
        <br>
        <br>
        <el-upload :auto-upload="false" accept=".xls,.xlsx" :limit="1" ref="uploadRef" :on-change="onChange"
          :on-remove="onRemove">
          <template #trigger>
            <el-button>第二步：选择文件</el-button>
          </template>
        </el-upload>
        <br>
        <br>
        <el-button @click="importData()">第三步：开始导入</el-button>
        <br>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import FormTable from "@/components/FormTable/index.vue"
import vForm from "./v-form.vue"
import { defineComponent, onMounted, reactive, ref, toRefs } from 'vue'
import { getListNewStanTechOrgPageList, delListNewStanTechOrgById, addBatchListNewStanTechOrg } from "@/api/api"
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import { cityList } from "@/utils/enum"

export default defineComponent({
  name: '',
  components: { FormTable, vForm },
  setup () {
    const uploadRef = ref()
    const dataMap = reactive({
      tableData: [],
      formRules: [
        {
          type: "input",
          field: "name",
          title: "名称",
          value: "",
        }
      ],
      searchForm: {
        name: "",
      },
      columns: [
        {
          label: "序号",
          type: "index",
          width: '70px'
        },
        {
          label: "名称",
          prop: "name",
        },
        {
          label: "所处领域",
          prop: "fieldStudy",
          showOverflowTooltip: true,
        },
        {
          label: "承担单位或组成单位",
          prop: "undertakingUnits",
          showOverflowTooltip: true,
        },
        {
          label: "推荐单位",
          prop: "recommendedUnits",
          showOverflowTooltip: true,
        },
        {
          label: "批次",
          prop: "batch",
        },
        {
          label: "联系人",
          prop: "contacts",
        },
        {
          label: "联系电话",
          prop: "contactNumber",
        },
        {
          label: "所在区",
          prop: "areaName",
        },

        {
          label: "创建时间",
          prop: "createTime",
          align: 'center',
          width: '160px'
        },
        {
          prop: 'operator',
          label: "操作",
          align: 'center',
          width: '120px'
        },
      ],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isDetail: false,
      isFabu: false,
      dialogForm: {},
      showImportDialog: false,
      importFile: ''
    })
    const methodsMap = reactive({
      openImportDialog () {
        dataMap.importFile = ''
        dataMap.showImportDialog = true
      },
      downloadTemplate () {
        //下载本地模板
        const a = document.createElement('a')  // 创建一个<a />标签
        a.href = 'static/shsxxbzhjszz.xls'
        a.download = '上海市新型标准化技术组织.xls' // 设置下载文件名
        a.style.display = 'none' // 隐藏a标签
        document.body.appendChild(a)  // 将a标签追加到文档对象中
        a.click()   // 点击，浏览器自动下载
        a.remove()  // 用完就删除<a />标签
      },
      onRemove () {
        dataMap.importFile = ''
      },
      onChange (file) {
        dataMap.importFile = file.raw
      },
      importData () {
        if (!dataMap.importFile)
        {
          ElMessage.error('请选择文件')
          return
        }
        let file = dataMap.importFile

        const reader = new FileReader()

        reader.onload = (evt) => {
          const data = new Uint8Array(evt.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          // 将工作表转换为JSON格式
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
          if (jsonData.length === 0)
          {
            ElMessage.error('文件内容为空')
            return
          }
          const FieldMap = {
            '名称': 'name',
            '所处领域': 'fieldStudy',
            '承担单位或组成单位': 'undertakingUnits',
            '推荐单位': 'recommendedUnits',
            '批次': 'batch',
            '联系人': 'contacts',
            '联系电话': 'contactNumber',
            '所在区': 'areaCode',
          }
          const headersName = jsonData[0]
          const headers = jsonData[0].map(header => FieldMap[header])
          const rows = jsonData.slice(1)
          if (headers.length != 8 || headers.filter(header => !header).length > 0)
          {
            message.error('文件模板错误，请检查文件模板是否与提供下载的模板一致')
            return
          }

          // 检查每行的数据完整性
          let missingFields = []
          let dataList = []
          rows.forEach((row, rowIndex) => {
            let item = {}
            for (let cellIndex = 0; cellIndex < row.length; cellIndex++)
            {
              const cell = row[cellIndex]
              if (!cell && headers[cellIndex] !== undefined)
              {
                missingFields.push(`<div>第 ${rowIndex + 2} 行的 ${headersName[cellIndex]}为空</div>`)
              } else
              {
                if (headers[cellIndex] === 'areaCode')
                {
                  let find = cityList.find(o => o.label.includes(cell))
                  if (find)
                  {
                    item['areaCode'] = find.value
                    item['areaName'] = find.label
                  } else
                  {
                    missingFields.push(`<div>第 ${rowIndex + 2} 行的 ${headersName[cellIndex]}异常</div>`)
                  }
                } else
                {
                  item[headers[cellIndex]] = cell
                }
              }
            }
            dataList.push(item)
          })
          if (missingFields.length > 0)
          {
            ElMessageBox.alert(
              missingFields.join(''),
              '发现缺少必填项，请检查',
              {
                dangerouslyUseHTMLString: true,
              }
            )
            return
          }
          addBatchListNewStanTechOrg(dataList).then(res => {
            if (res.data.code == 0)
            {
              ElMessage.success("导入成功")
              dataMap.dialogVisible = false
              setTimeout(() => {
                methodsMap.getDatas()
              }, 500)
            } else
            {
              ElMessage.error(res.data.message)
            }
          })

          // bookingCategoryApi.batchAdd(dataList).then(res => {
          //   SmartLoading.hide()
          //   message.success(`导入成功`)
          //   queryData()
          //   hideImportModal()
          // }).catch(e => {
          //   smartSentry.captureError(e)
          //   SmartLoading.hide()
          // })
        }

        reader.readAsArrayBuffer(file)

      },
      del ({ id }) {
        delListNewStanTechOrgById(id).then(res => {
          ElMessage({
            type: "success",
            message: "删除成功",
          })
          setTimeout(() => {
            methodsMap.getDatas()
          }, 500)
        })
      },
      detail (items) {
        dataMap.dialogForm = items
        dataMap.isDetail = true
        dataMap.isFabu = false
        dataMap.dialogVisible = true
      },
      edit (items) {
        if (items)
        {
          dataMap.dialogForm = items
        } else
        {
          dataMap.dialogForm = {}
        }
        dataMap.dialogVisible = true
      },
      changeTableData (pageNum, pageSize) {
        dataMap.pageIndex = pageNum
        dataMap.pageSize = pageSize
        methodsMap.getDatas()
      },
      getDatas () {

        getListNewStanTechOrgPageList({
          "pageNum": dataMap.pageIndex,
          "pageSize": dataMap.pageSize,
          rules: [
            {
              "field": "name",
              "opType": "Contains",
              "data": dataMap.searchForm.name
            }
          ]
        }).then((res) => {
          dataMap.tableData = res.data.data.list
          dataMap.total = res.data.data.total
        })
      },
      queryTable (params) {
        dataMap.searchForm = params || {}
        dataMap.pageIndex = 1
        methodsMap.getDatas()
      }
    })
    onMounted(() => {
      methodsMap.getDatas()
    })
    return {
      ...toRefs(dataMap),
      ...toRefs(methodsMap),
      uploadRef
    }
  },
})
</script>
<style lang="scss" scoped></style>